<?php

namespace App\Console\Commands;

use App\Events\PostSaved;
use App\User;
use Carbon\Carbon;
use Doctrine\Common\Cache\Cache;
use Illuminate\Console\Command;
use Illuminate\Database\Query\Expression;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\Redis;

class Test extends Command
{
    static $HtmlClassOperator = '<b class="kg-operator">%s</b>';
    static $HtmlClassName = '<b class="kg-name">%s</b>';
    static $HtmlClassMobile = '<b class="kg-mobile">%s</b>';
    static $HtmlClassText = '<b class="kg-text">%s</b>';
    static $HtmlClassTag = '<b class="kg-tag">%s</b>';
    static $HtmlClassDate = '<b class="kg-date">%s</b>';
    static $HtmlClassPrice = '<b class="kg-price">%.2f</b>';

    protected static $user = [];
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'test';
    private $signature2 = '222';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    function cb1($a)
    {
        return [$a];
    }

    function cb2($a, $b)
    {
        return [$a, $b];
    }

    public function handle(User $user)
    {


        dd(strlen('_token=qP5lckKRNigolwZJ8oF11aaA440P6qZLaVwxuhd3'));
//      $data =   DB::table('users')
//            ->select(['id','name'])
//            ->whereExists(function ($query) {
//                $query->select(['idcard.user_id','idcard.city'])
//                    ->from('identity_cards as idcard')
//                    ->whereRaw('idcard.user_id = users.id');
//            })
//            ->whereExists(function ($query) {
//                $query->select(['order.user_id','order.order_name'])
//                    ->from('oc_order as order')
//                    ->whereRaw('order.user_id = users.id');
//            })
//            ->get();

        $data =    DB::table('users')
            ->select(['users.id','users.name'])
        ->join('identity_cards as idcard','idcard.user_id','=','users.id')
        ->join('oc_order','oc_order.user_id','=','users.id')
            ->get();
dd($data);

// [5, 6, 7, 8, 9, 10]


        $sql = DB::table('users')->where('id', '<', 4)->select('id', 'name');

//        $data = DB::table('users as u')
//            ->Join(new Expression('(' . $this->get_complete_sql($sql) . ') as tt'), 'tt.id', '=', 'u.id')
//            ->get();

        $data = DB::table(new Expression('(' . $this->get_complete_sql($sql) . ') as tt'))->get();

        dd($data);
//        $collection = collect(['product_id' => 1, 'name' => 'Desk']);
//
//        $collection->put('product_id', 2);
//
//        dd($collection->all());

// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]
        $arr2 = [
            ['product_id' => 'prod-100', 'name' => 'Desk'],

            ['product_id' => 'prod-200', 'name' => 'lmk'],
        ];
        $arr1 = [333 => ['sss' => 'ddd']];

        $arr3 = [0 => 'lmk'];
        $arr4 = [0 => 22];
//        dd($arr3 + $arr4);
        dd(array_merge($arr3, $arr4));

        $collection = collect([
            ['product_id' => 'prod-100', 'name' => 'Desk'],

            ['product_id' => 'prod-200', 'name' => 'lmk'],
        ]);
        $collection->prepend(['ssss' => 'ssss'], 1);

        dd($collection->toArray());

        $keyed = $collection->keyBy('product_id');
        $keyed2 = $collection->groupBy('product_id');

        dump($keyed);
        dd($keyed2);

        /*
            [
                'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
                'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
            ]
        */


//    DB::table('posts')->leftJoin()
        $data = collect([1, 2, 4, 4, 5, 5, 6, null, 0, false]);
        dd($data->unique()->filter()->values());
        foreach ($data as $v) {
            if (is_null($v->namesssddaq)) {
                dd(222);
            }
        }

        dd(111);


        $collection = collect([
            ['product' => 'Desk', 'price' => 200],
            ['product' => 'Chair', 'price' => 100],
            ['product' => 'Bookcase', 'price' => 150],
            ['product' => 'Door', 'price' => '100'],
            ['product' => 'sss', 'price' => 1],
        ]);

        $filtered = $collection->filter(function ($value) {
            return $value['price'] <=> 100;
        })->toArray();

        dd($filtered);

        /*
            [
                ['product' => 'Chair', 'price' => 100],
                ['product' => 'Door', 'price' => 100],
            ]
        */
        dd($collection->toArray());

// ['taylor' => 'name', 'laravel' => 'framework']

// [0, 1, 2]
        $collection = collect();

        $collection2 = $collection->whenEmpty(function ($collection) {
            return $collection->push('adam');
        });
        $collection2->push('lmk');
        dump($collection2->all());
        dd($collection->all());

// ['adam']


//        $collection = collect(['michael', 'tom']);
//
//        $collection->whenEmpty(function($collection) {
//            return $collection->push('adam');
//        }, function($collection) {
//            return $collection->push('taylor');
//        });
//
//        $collection->all();

// ['michael', 'tom', 'taylor']
//        $collection = collect([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);

//        dd($collection->collapse()->toArray());


// [1, 2, 3, 4, 5, 6, 7, 8, 9]
        $collection = collect([[1, 2], [4, 5]]);

        $collection = $collection->unless(false, function ($collection) {
            return $collection->push(['a', 'b']);
        });
        dd($collection);
//        $collection = collect([1, 2, 3]);
//
//        $collection->unless(true, function ($collection) {
//            return $collection->push(4);
//        });
//
//        $collection->unless(false, function ($collection) {
//            return $collection->push(5);
//        });

        dd($collection->all());

// [1, 2, 3, 5]
        dd($collection->all());

        /*
            [
                ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
                ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
            ]
        */

// [2, 4, 6, 8, 10]


        $res = array_map('strtoupper', ['name' => 'Sally', 'age' => 'hhh']);
        dd($res);
        collect([2, 4, 3, 1, 5])
            ->sort()
            ->tap(function ($collection) {
                dump($collection->values()->toArray());
//                Log::debug('Values after sorting', $collection->values()->toArray());
            })
            ->shift();

        dd(112);

        $parentIds = [1, 2, 3, 5];
        $childIds = [1, 2, 4];
        $res = array_diff($parentIds, $childIds);
        dd($res);//2,5
// ['gmail.com' => 2, 'yahoo.com' => 1]


        dd($collection);

        $country = 'E';
        $users = User::query()->select(['name', 'email'])->get()->each(function ($item) use ($country) {

            if ($country === 'E') {
                $item->sex = $item->name . 'womens';//四捨五入phpphp
            }

        })->toArray();


        dd($users);

        dd($this->http_get_daili());


        $res = DB::table('users')->where(['id' => 1])->update(['created_at' => DB::raw('updated_at')]);


        dd($res);
//        dd($user->getuser());
        $users = DB::table('users')->select('name', 'email', 'id')->limit(3)->get()->toArray();


        foreach ($users as $v) {
            $user->setUser($v);
        }


        dd(11);
        $res = [];

        $users->each(function ($item) use (&$res) {
            $item = get_object_vars($item);
            $item['name'] = $item['name'] ?: '???';
            $item['email'] = $item['email'] ?: '!!!';

            unset($item['id']);
            $res[] = $item;
        });


        dd($res);
        $row = get_object_vars($obj);
        dd($row);
        $email = 'james@example.com';
        $employees = collect($arr);

        $employees = (array)($employees);
        dd($employees);
        $employees->each(function ($item, $key) use ($email) {
            dd($item);
            $row = get_object_vars($item);
            dd($row);
        });
        dd(111);
        $employees->duplicates()->dd();

// [2 => 'Developer']

// [2 => 'a', 4 => 'b']

// false
// ['name' => 'George', 'age' => 29]

// [1, 2, 3, 4, 5, 6, 7, 8, 9]

//        DB::table('users')
//            ->where('name', '=', 'John')
//            ->whereNested(function ($query) {
//                $query->where('email', '>', 100)
//                    ->orWhere('password', '=', 'Admin');
//            })
//            ->where(function ($query) {
//                $query->where('email', '>', 100)
//                    ->orWhere('password', '=', 'Admin');
//            })
//            ->havingRaw('email > ? or password = ?', [100, 'Admin'])
//            ->get();

        dd(111);

        $aa = DB::table('users')
            ->join('oc_order', function ($join) {
                $join->on('users.id', '=', 'oc_order.user_id')
                    ->where('oc_order.user_id', '>', 1);
            })
            ->get();

        dd($aa);


        $users = DB::table('users')
//            ->join('identity_cards', 'users.id', '=', 'identity_cards.user_id')
            ->crossJoin('oc_order')
            ->select('users.name', 'users.id', 'oc_order.order_name')
            ->get();

        dd($users);

        //获取用户信息
        $user = DB::table('users')->where('id', '<', 3)->get()->map(function ($item) {
            return (array)$item;
        })->toArray();
        dump($user);
        $user2 = DB::table('users')->where('id', '<', 3)->get()->map(function ($item) {
            return get_object_vars($item);
        })->toArray();
        dd($user2);
//        $user = User::query()->get()->map(function ($item) {
////            $item->class = 'kg-user';
////            $item->class2 = 'kg-user';
//            return get_object_vars($item);
//        })->toArray();


        dd($user);
        $this->select('id', 'name', 'description', 'sort');

        //laravel 子查询

        $arr = [1, 2, 4];
        $r = array_reduce($arr, function ($carry, $item) {
            dump($carry);
            dd($item);

        }, 0);
        dd($r);

        $url = '';
        $a = 'lkm';
        $url .= '&name=' . urlencode(html_entity_decode($a, ENT_QUOTES));
        dd($url);
// [2 => 'Developer']
//        $field = array_map(function ($val){
//            return 'a.'.$val;
//        },$field);


        dd($employees);

        $fa = \DB::table('users as u')->leftJoin('identity_cards as i', 'i.user_id', '=', 'u.id')
            ->where(function ($q) {
                $q->where(function ($qq) {
                    $qq->where('u.id', 1)->where(function ($qqq) {
                        $qqq->where('u.name', 'lmk')->orWhere('u.name', 'hdd');
                    });
                })->orWhere(function ($qq) {
                    $qq->where('i.id', 3)->orWhere('i.id', 4);
                });
            })->where('u.name', 'name')->get();


//      $fa = User::query()->with('identity_card')->where('id','>',1)->get();
        dd($fa);

//        User::query()->leftJoin('')
//        $post = ['id' => 2, 'title' => '标题222'];

//        event(new PostSaved($post));
        return;
//        Event::dispatch(new PostSaved($post));

//        dd(1);
        //读取操作
        $dir = 'C:\Users\lmk\Desktop\111\F1-SEQ-M13F\/';
        //首先看每个文件夹中的文件哪些会发生冲突

        $res = $this->scanFile($dir);

        dd($res);


//        $data = ['a', 'b', 'c'];
//        foreach ($data as $k => $v) {
//
//            $v = &$data[$k];
//        }
//
//
//        $a = 0.1;
//        $b = 0.7;
//
//        if ($a + $b == 0.8) {
//
//            echo true;
//        } else {
//            echo false;
//        }
//        $a = 0;
//        $b = 0;
//
//        if ($a = 3 > 0 || $b = 3 > 0) {
//            $a++;
//            $b++;
//        }
//
//        echo $a,$b;
        $str = false;
        if (!0) {
            echo 111;
        }


//        sleep(3);
//        $this->line('111');


//         $res = $this->transTemplate2TextHtml('开通 %s，起止：%s ~ %s，席位数：%s人，金额：%s，操作人：%s',
//            sprintf(static::$HtmlClassText, 'DMG'),
//            sprintf(static::$HtmlClassDate, '2020-04-01'),
//            sprintf(static::$HtmlClassDate, '2020-05-01'),
//            sprintf(static::$HtmlClassText, 100),
//            sprintf(static::$HtmlClassPrice, 100.20),
//            sprintf(static::$HtmlClassOperator, 'admin')
//        );
//
//
//
//        dd($res);
        //


//        $this->info('111');
//        $users = User::query()->get(['name', 'email'])->toArray();
//
//        $headers = ['Name', 'Email'];
//
//
//        $this->table($headers, $users);

//        $arr = ['a'=>['name'=>'sss','age'=>11],['b'=>['name'=>'ddd','age'=>23]]];
//
//        $arr = $this->array_remove_by_key($arr,'age');
//
//        dd($arr);
    }


    public function get_complete_sql($builder)
    {
        $bindings = $builder->getBindings();

        $i = 0;
        return preg_replace_callback('/\?/', function ($matches) use ($bindings, &$i) {
            return "'" . addslashes($bindings[$i++] ?? '') . "'";
        }, $builder->toSql());
    }

    public function select($columns = ['*'])
    {

        $columns = is_array($columns) ? $columns : func_get_args();
        dd($columns);
    }

    /**
     * 测试代理
     * @return bool|string
     */
    function http_get_daili()
    {
        $curl = curl_init();
//        curl_setopt($ch, , ); //
//        curl_setopt($ch, CURLOPT_PROXY, "112.65.219.72"); //代理服务器地址
//        curl_setopt($ch, , 80); //代理服务器端口
////curl_setopt($ch, CURLOPT_PROXYUSERPWD, ":"); //http代理认证帐号，username:password的格式
//        curl_setopt($ch, , ); //使用http代理模式
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://httpbin.org/ip',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_PROXYAUTH => CURLAUTH_BASIC,//代理认证模式
            CURLOPT_PROXY => '72.169.67.17',//代理认证模式
            CURLOPT_PROXYPORT => 87,
            CURLOPT_PROXYTYPE => CURLPROXY_HTTP,//代理认证模式
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
                'Connection:  keep-alive',
                'User-Agent:  Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat',
                'content-type:  application/json',
                'Accept-Encoding:  gzip, deflate, br'
            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        return $response;
    }

    function scanFile($path)
    {
        global $result;

        $files = scandir($path);

        foreach ($files as $file) {
            if ($file != '.' && $file != '..') {
                if (is_dir($path . '/' . $file)) {
                    $this->scanFile($path . '/' . $file);
                } else {
                    $result[$path][] = basename($file);
                }
            }

        }

        //处理
        foreach ($result as $v)
            $tmp_name = str_replace('F1-SEO', 'F78874', $v);


        return $result;

    }

    function transTemplate2TextHtml(string $template, string ...$args): array
    {
        return [
            'text' => sprintf($template, ... array_map(function ($v) {
                return strip_tags($v);
            }, $args)),
            'html' => sprintf($template, ... $args)
        ];
    }

    /**
     * 根据key删除数组中指定元素
     * @param array $arr 数组
     * @param string/int  $key  键（key）
     * @return array
     */
    private function array_remove_by_key($arr, $key)
    {
        if (!array_key_exists($key, $arr)) {
            return $arr;
        }
        $keys = array_keys($arr);
        $index = array_search($key, $keys);
        if ($index !== FALSE) {
            array_splice($arr, $index, 1);
        }

        return $arr;
    }
}
